In this example, we will create a Car
constructor function that defines the brand, model, and year of the car.
<!DOCTYPE html>
<html>
<body>
<p id="carInfo"></p>
<script>
function Car(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
// Adding a method to describe the car
this.getCarInfo = function() {
return `This car is a ${this.year} ${this.brand} ${this.model}.`;
};
}
const myCar = new Car("Toyota", "Corolla", 2020);
// Display the car info using the getCarInfo method
document.getElementById("carInfo").innerText = myCar.getCarInfo();
</script>
</body>
</html>
To create instances of the Car
object, use the new
keyword. Once created, the instance will have access to the properties and methods defined in the constructor.
<!DOCTYPE html>
<html>
<body>
<script>
function Car(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
// Adding a method to describe the car
this.getCarInfo = function() {
return `This car is a ${this.year} ${this.brand} ${this.model}.`;
};
}
// Creating instances of Car
const car1 = new Car('Toyota', 'Corolla', 2020);
const car2 = new Car('Tesla', 'Model 3', 2022);
// Using the method to get car details
console.log(car1.getCarInfo()); // Output: This car is a 2020 Toyota Corolla.
console.log(car2.getCarInfo()); // Output: This car is a 2022 Tesla Model 3.
</script>
</body>
</html>
Enter details below to create a new car object and display its information: